/**
 * @(#) ZhuBaJieAcquisition.java
 *
 * @author lihg
 * @version V1.0 2013-10-1
 *
 * Copyright (C) 2010,2013 , Lihg
 */

/**
 * 
 */
package cn.com.dshome.acquisition.service.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import cn.com.dshome.acquisition.exception.AcquisitionException;
import cn.com.dshome.acquisition.service.Acquisition;
import cn.com.dshome.acquisition.utils.HttpClientUtils;
import cn.com.dshome.acquisition.utils.StringUtils;
import cn.com.dshome.acquisition.vo.BaseInformation;

/**
 * 
 * Purpose:采集猪八戒网信息
 * 
 * @author lihg
 * @see
 * @since
 */
@Service("bajieAcquisition")
public class ZhuBaJieAcquisition implements Acquisition {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8393449676483165765L;

	private String URI =  "http://www.t5.zhubajie.com/user/" ;//"http://www.t5.zhubajie.com/topic/381/t.html" ; //只采集开发页面内容

	@Autowired
	@Qualifier("httpClientUtils")
	private HttpClientUtils hcu ;


	//记录日志
	private Log log = LogFactory.getLog(ZhuBaJieAcquisition.class) ;

	@Autowired
	private TaskExecutor taskExecutor ;

	private String preUrl ;
	/* (non-Javadoc)
	 * @see cn.com.dshome.acquisition.service.Acquisition#listInformation(cn.com.dshome.acquisition.vo.BaseInformation)
	 */
	@Override
	public <T extends BaseInformation> List<T> listInformation(Class<T> clazz)
	throws AcquisitionException {
		//获取主页面数据
		String responseMessage = convertByteToString(hcu.getResponseMessage(URI)) ;
		//解析数据
		Document document = Jsoup.parse(responseMessage) ;
		//查找各个章节信息
		Elements chapters = document.select("div.topic>h4>a") ;
		//开发章节
		Element develop = null ;
		for(Element chapter : chapters){
			String msg = chapter.text() ;
			if(StringUtils.hasLength(msg) && "开发".equals(msg.trim())){
				develop = chapter ;
				break ;
			}
		}
		//开发章节URL
		String developUrl = develop.attr("href") ;
		preUrl = developUrl.substring(0,developUrl.indexOf("/",10)) ;
		//开发页面数据
		String developPageInformation = convertByteToString(hcu.getResponseMessage(developUrl)) ;
		//解析数据
		Document developDoc = Jsoup.parse(developPageInformation) ;
		//获取详细信息
		fetchMessage(developDoc) ;
		return null;
	}

	/**
	 * 获取详细信息
	 * @param developDoc
	 * @throws AcquisitionException
	 */
	private void fetchMessage(Document developDoc) throws AcquisitionException{
		Elements needs = developDoc.select("dl.user-information dd.mint>p>a[rel]") ;
		for(final Element element : needs){
			taskExecutor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						String url = element.attr("href");
						String responseMessage = convertByteToString(hcu.getResponseMessage(url));
						Document document = Jsoup.parse(responseMessage);
						Element titleElement = document.getElementById("ed-tit");
						String title = titleElement.select("h1").first().html();
						String details = document.getElementById("work-more").children().html();//.replaceAll("\\&.*?;|<.*?>","") ;
						String money = titleElement.getElementById("priceComp").text();
						String publishTime = document.select("p#j-receiptcon > span.time").text();
						log.info("【" + title + "】\t发布时间【" + publishTime + "】\t悬赏 【" + money + " 】\t 要求【" + details + "】");
						String submitUrl = document.getElementById("caseSubmit").attr("act-url") ;
						//						submit(preUrl + submitUrl) ;
					} catch (Exception e) {
						log.error("获取详细信息失败" ,e) ;
					}
				}
			}) ;

		}
		//下一页URL
		Element nextPage = developDoc.select("div.pagination>ul>li>a").last() ;
		String nextPageUrl = preUrl + nextPage.attr("href") ;
		//获取下一页信息
		fetchMessage(Jsoup.parse(convertByteToString(hcu.getResponseMessage(nextPageUrl)))) ;
	}


	private void submit(String url) throws AcquisitionException{
		String content = "你好，看了你的需求 可以完成 详" ;
		String ag = "1"  ;
		String hidden = "0" ;
		String type= "21" ;
		String usercard = "0" ;
		String spam_token = "hvysevpacnujbte:cIiLdNtaWLlVafdirDgdyWabH-94458gLYqTpNCTUGrQxKdnzRRH" ;
		NameValuePair[] params = new NameValuePair[6] ;
		params[0] = new BasicNameValuePair("content",content) ;
		params[1] = new BasicNameValuePair("ag",ag) ;
		params[2] = new BasicNameValuePair("hidden",hidden) ;
		params[3] = new BasicNameValuePair("type",type) ;
		params[4] = new BasicNameValuePair("usercard",usercard) ;
		params[5] = new BasicNameValuePair("spam_token",spam_token) ;
		String responseMessage  = convertByteToString(hcu.getResponseMessage(url,params)) ;
		log.info(responseMessage) ;
	}


	private void login() throws AcquisitionException{
		String loginUrl = "https://login.zhubajie.com/" ;
		//		System.out.println(convertByteToString(hcu.getResponseMessage(loginUrl)));
		String login  = loginUrl + "login/dologin" ;
		NameValuePair[] params = new NameValuePair[2] ;
		params[0] = new BasicNameValuePair("username","aaa") ;
		params[1] = new BasicNameValuePair("password","aaa") ;
		System.out.println(convertByteToString((byte[])hcu.simulateOperation(login,params).get(hcu.RESPONSE_MESSAGE))) ;
	}

	/**
	 * Byte转String
	 * @param content
	 * @return
	 */
	private String convertByteToString(byte[] content){
		try {
			String charSet = hcu.getChartSet() ;
			if (StringUtils.hasLength(charSet)) {
				return StringUtils.byteArray2String(content, charSet);
			} else {
				return StringUtils.byteArray2String(content);
			}
		} catch (Exception e) {
			log.error("convertByteToString failed " ,e) ;
			return null ;
		}
	}
}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2013-10-1 下午06:36:59 lihg 创建版本
 */